/**
 * @param {character[][]} grid
 * @return {number}
 */
var numIslands = function(grid) {
  let count = 0;
  function dfs(indexI, indexJ) {
    grid[indexI][indexJ] = '0';
    if(indexI - 1 >= 0 && grid[indexI - 1][indexJ] == '1') {
      dfs(indexI - 1, indexJ);
    }
    // 下
    if(indexI + 1 < grid.length && grid[indexI + 1][indexJ] == '1') {
      dfs(indexI + 1, indexJ);
    }
    // 左
    if(indexJ - 1 >= 0 && grid[indexI][indexJ - 1] == '1') {
      dfs(indexI, indexJ - 1);
    }
    // 右
    if(indexJ + 1 < grid[0].length && grid[indexI][indexJ + 1] == '1') {
      dfs(indexI, indexJ + 1);
    }
  }
  for(let i = 0; i < grid.length; i++) {
    for(let j = 0; j < grid[0].length; j++) {
      if(grid[i][j] == '0') continue;
      else {
        dfs(i, j);
        count++;
      }
    }
  }
  return count;
};
let grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
];
console.log(numIslands(grid));
grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
console.log(numIslands(grid));

